<template>
  <div
    class="func"
    :class="{'host--adjust-item': hostAs === 'adjust-item'}"
  >
    <el-radio-group
      v-model="pageConfigModel.goodsChooseType"
      @change="handleGoodsChooseTypeChange"
    >
      <el-radio
        v-if="!disableTypes?.includes('manual')"
        label="manual"
      >
        手动选择
      </el-radio>
      <el-radio
        v-if="!disableTypes?.includes('category')"
        label="category"
      >
        商品分类
      </el-radio>
      <el-radio
        v-if="!disableTypes?.includes('all')"
        label="all"
      >
        全部商品
      </el-radio>
    </el-radio-group>

    <div class="sub-options">
      <div
        v-if="pageConfigModel.goodsChooseType === 'manual'"
        class="sub-option sub-option__vertical sub-option__stretch"
      >
        <div class="control-component">
          <div
            class="extra-div"
            style="width: 100%"
            @click="addItem"
          >
            <p>+添加</p>
          </div>
        </div>

        <div class="value">
          <Gallery
            :list="chooseGoodsList"
            src-key="thumbnailUrl"
            alt-key="name"
            style="margin-top: 10px"
            @close="deleteChooseGoods"
          />
        </div>
      </div>

      <div
        v-if="pageConfigModel.goodsChooseType === 'category'"
        class="sub-option sub-option__vertical"
      >
        <!--        <div class="label label__64">-->
        <!--          商品分类-->
        <!--        </div>-->

        <div class="control-component">
          <el-select
            v-model="pageConfigModel.goodsChooseCate"
            multiple
            placeholder="请选择商品分类"
          >
            <el-option
              v-for="item in goodsCateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </div>
      </div>
    </div>
  </div>

  <goods-select-2
    v-model:show="dialogFormVisible"
    :values="chooseGoodsList"
    multi-select
    :search-form="goodsSelectSearchForm"
    @confirm="submitForm"
  />
</template>

<script setup lang="ts">
import {
  ISelectGoodsSettingPageConfig,
  selectGoodsSettingPageConfig
} from "@/views/activity/actApp/components/default/operationComponents/selectGoodsSetting/index";
import { Ref, WritableComputedRef } from "vue";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import { getAllCategory, getPage2 } from "@/api/actapp";
import { IGoodsPageRow } from "@/api/modules/pointsMall";
import GoodsSelect2 from "@/components/goodsCenter/GoodsSelect2.vue";
import { debounce } from "@/utils";

const props = withDefaults(defineProps<{
  pageConfig: ISelectGoodsSettingPageConfig;
  disableTypes?: ISelectGoodsSettingPageConfig['goodsChooseType'][];
  hostAs: "func" | "adjust-item"
}>(), {
  disableTypes: () => ([]),
  pageConfig: () => ({
    ...selectGoodsSettingPageConfig
  })
});

const emits = defineEmits<{
  (e: "update:page-config", value: ISelectGoodsSettingPageConfig): void
}>();

const { mallConfig } = useMallConfig()

const pageConfigModel:WritableComputedRef<ISelectGoodsSettingPageConfig> = computed({
  get() {
    return props.pageConfig;
  },
  set(newValue) {
    emits("update:page-config", newValue)
  }
})

const handleGoodsChooseTypeChange = (val: string) => {
  if (val === 'category' && !goodsCateList.value.length) {
    getGoodsCateList()
  }

  // 清空手动选择
  pageConfigModel.value.imgList = {
    mallId: mallConfig.value.id,
    goodsId: []
  }

  chooseGoodsList.value = [];

  // 清空分类
  pageConfigModel.value.goodsChooseCate = []
}

const dialogFormVisible: Ref<boolean> = ref(false);
const goodsSelectSearchForm = ref({
  mallId: undefined,
})
// 增
const addItem = () => {
  goodsSelectSearchForm.value.mallId = mallConfig.value.id
  dialogFormVisible.value = true;
};

// 删
const deleteChooseGoods = ({ index }: { item: IGoodsPageRow, index: number }) => {
  ElMessageBox.confirm("确定删除？", "提示", {
  }).then(() => {
    chooseGoodsList.value.splice(index, 1);
    changeConfigImgList()
  }).catch(() => {
    // cancel
  })
}

// 改
const changeConfigImgList = () => {
  pageConfigModel.value.imgList = {
    mallId: mallConfig.value.id,
    goodsId: chooseGoodsList.value.map(item => item.id),
  }
}

// 查
const goodsCateList:Ref<any[]> = ref([]);
const getGoodsCateList = async () => {
  const rs = await getAllCategory({ id: mallConfig.value.id });
  goodsCateList.value = rs.payload ?? [];
}

// 结束弹窗商品选择
const chooseGoodsList: Ref<{ id: number }[]> = ref([]);
const submitForm = (selected: any[]) => {
  chooseGoodsList.value = JSON.parse(JSON.stringify(selected));
  changeConfigImgList()
  dialogFormVisible.value = false;
};

// 根据goodsId 获取商品
const getAllGoodsDetail = async () => {
  if (!pageConfigModel.value.imgList?.goodsId?.length) {
    chooseGoodsList.value = []
    return
  }

  const rs = await getPage2({
    mallId: mallConfig.value.id,
    goodsIds: pageConfigModel.value.imgList.goodsId,
    currentPage: 1,
    showCount: -1,
  });

  if (rs.code === 200) {
    chooseGoodsList.value = rs.payload ?? [];
  }
}

const debouncedGetAllGoodsDetail = debounce(getAllGoodsDetail, 700, false);

watch(() => pageConfigModel, () => {
  if (!pageConfigModel.value.imgList) {
    // 历史改动原因，这里也要存一下
    pageConfigModel.value.imgList = {
      mallId: mallConfig.value.id,
      goodsId: []
    }
  }
  // console.log("------------------------pageConfigModel-----------------", pageConfigModel);
  // if (!pageConfigModel.value?.imgList?.mallId) {
  //   pageConfigModel.value.imgList.mallId = mallConfig.value.id;
  // }

  debouncedGetAllGoodsDetail();
}, {
  immediate: true,
  deep: true,
})


onMounted(() => {
  getGoodsCateList();
})
</script>

<style scoped lang="scss">
@use "@/views/activity/actApp/components/default/styles/operation.scss";

/* 组件作为内嵌的adjustItem 存在 */
.host--adjust-item {
  border: unset;
  padding: unset;

  .sub-options .sub-option {
    padding: unset;
  }
}
</style>
